package main

import (
	"time"
	"math/rand"
	"match-spider/util/prop"
	"github.com/gocolly/colly"
	"fmt"
	"regexp"
	"strings"
	"github.com/PuerkitoBio/goquery"
	"match-spider/util/pg"
)
func fetchJincai(date string)  {
	url:="http://www.310win.com/buy/jingcai.aspx?date="+date

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"

	c.OnHTML("#MatchTable", func(e *colly.HTMLElement) {
		dateString:=""
		e.DOM.Find("tr").Each(func(i int, s *goquery.Selection) {
			classText, e := s.Attr("class")
			if e && classText == "niDate" {
				niDate := s.Find("td").Eq(0).Text()
				reg, _ := regexp.Compile("[\\d]+年[\\d]+月[\\d]+日")
				str := reg.FindString(niDate)
				date, _ := time.Parse("2006年01月02日", str)
				dateString = date.Format("2006-01-02")

			}
			_,e= s.Attr("matchid")

			if e {

				number := s.Find("td").Eq(0).Text()

				dataNode := s.Find("td").Eq(11)
				link, _ := dataNode.Find("a").Eq(0).Attr("href")
				link = strings.Replace(link, "/handicap/", "", -1)
				matchId := strings.Replace(link, ".html", "", -1)
				sql := "update t_match set is_jc=1,jc_number=$1 where is_jc=0 and id=$2"
				fmt.Println(matchId)
				pg.UpdateOrDelete(sql, number, matchId)

			}
		})
	})
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)

	})

	c.Visit(url)
}
func main()  {

	startAt:=prop.Get("match","date.start")
	endAt:=prop.Get("match","date.end")
	startTime,_:=time.Parse("2006-01-02",startAt)
	endTime,_:=time.Parse("2006-01-02",endAt)

	for{
		if(endTime.Sub(startTime).Hours()<0){
			break
		}

		nextTimeString:=time.Unix(startTime.Unix(),0).Format("2006-01-02")
		fetchJincai(nextTimeString)
		seed:=100+rand.Intn(300)
		time.Sleep(time.Millisecond*time.Duration(seed))
		startTime=startTime.Add(time.Hour*24)
	}
}
